#!/bin/sh

uci_write_config() {
	uci -q set "cpufreq.cpufreq.governor$1"="$2"
	[ -n "$3" ] && uci -q set "cpufreq.cpufreq.minfreq$1"="$3"
	[ -n "$4" ] && uci -q set "cpufreq.cpufreq.maxfreq$1"="$4"
	[ -n "$5" ] && uci -q set "cpufreq.cpufreq.sdfactor$1"="$5"
	[ -n "$6" ] && uci -q set "cpufreq.cpufreq.upthreshold$1"="$6"
	uci -q commit cpufreq
}

[ "$(uci -q get cpufreq.global.set)" -eq "1" ] && exit 0

CPU_FREQS="$(cat '/sys/devices/system/cpu/cpufreq/policy0/scaling_available_frequencies')"
CPU_MIN_FREQ="$(cat '/sys/devices/system/cpu/cpufreq/policy0/scaling_min_freq')"
CPU_MAX_FREQ="$(cat '/sys/devices/system/cpu/cpufreq/policy0/scaling_max_freq')"
CPU_POLICYS="$(find '/sys/devices/system/cpu/cpufreq/policy'* -maxdepth 0 | grep -Eo '[0-9]+')"
SOC="$(strings '/proc/device-tree/compatible' | tail -n1)"

source "/etc/openwrt_release"
case "$DISTRIB_TARGET" in
	"bcm27xx/bcm2710")
		uci_write_config 0 ondemand 600000 "$CPU_MAX_FREQ" 10 50
		;;
	"bcm27xx/bcm2711"|\
	"bcm27xx/bcm2712")
		uci_write_config 0 schedutil
		;;
	"ipq40xx/generic")
		uci_write_config 0 performance 200000 "$CPU_MAX_FREQ"
		;;
	"ipq806x/generic")
		uci_write_config 0 performance 600000 "$CPU_MAX_FREQ"
		# IPQ8064/5
		echo "$CPU_POLICYS" | grep -q "1" && uci_write_config 1 performance 600000 1200000
		;;
	"mediatek/mt7622")
		uci_write_config 0 ondemand 600000 1350000 10 50
		;;
	"qualcommax/ipq60xx"|\
	"qualcommax/ipq807x")
		uci_write_config 0 schedutil
		;;
	"rockchip/armv8")
		case "$SOC" in
		"rockchip,rk3328")
			uci_write_config 0 schedutil 816000 1512000
			;;
		"rockchip,rk3399")
			uci_write_config 0 schedutil 600000 1608000
			uci_write_config 4 schedutil 600000 2016000
			;;
		"rockchip,rk3566"|\
		"rockchip,rk3568")
			uci_write_config 0 schedutil 816000 "$CPU_MAX_FREQ"
			;;
		"rockchip,rk3576")
			uci_write_config 0 schedutil 1008000 2208000
			uci_write_config 4 schedutil 1008000 2304000
			;;
		"rockchip,rk3582"|\
		"rockchip,rk3583"|\
		"rockchip,rk3588"|\
		"rockchip,rk3588j"|\
		"rockchip,rk3588s")
			uci_write_config 0 schedutil
			uci_write_config 4 schedutil
			uci_write_config 6 schedutil
			;;
		esac
		;;
	"sunxi/cortexa53")
		case "$SOC" in
		"allwinner,sun50i-h6")
			uci_write_config 0 schedutil 888000 "$CPU_MAX_FREQ"
			;;
		"allwinner,sun50i-h616"|\
		"allwinner,sun50i-h618")
			uci_write_config 0 schedutil 936000 "$CPU_MAX_FREQ"
			;;
		*)
			uci_write_config 0 schedutil
			;;
		esac
		;;
esac

exit 0
